package servlet.user;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet(name = "CodeServlet", value = "/code")
public class CodeServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 响应的类型为图片
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);

        // 创建一个图片对象
        int width = 100, height = 30;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

        // 获取图形上下文
        Graphics g = image.getGraphics();

        // 设置背景颜色
        g.setColor(new Color(0xDCDCDC));
        g.fillRect(0, 0, width, height);

        // 设置字体和颜色
        g.setColor(new Color(19,148,246));
        g.setFont(new Font("Arial", Font.BOLD, 20));

        // 随机生成的字符串
        Random random = new Random();
        String rand = Integer.toString(random.nextInt(9999));
        //将验证放到session
        request.getSession().setAttribute("code", rand);
        g.drawString(rand, 10, 20);

        // 图像噪声
        for (int i = 0; i < 50; i++) {
            int x = random.nextInt(width);
            int y = random.nextInt(height);
            g.drawOval(x, y, 0, 0);
        }

        // 输出图片
        ImageIO.write(image, "jpeg", response.getOutputStream());

        // 释放资源
        g.dispose();
        image.flush();
    }
}

